/**
 * 订单页面
 */
const express = require('express')
const userorder = express.Router()

// 引入数据库模块
const db = require('../../utils/db')

// 导入文件上传解析模块
const getformidable = require('../../utils/myformidable')
const fs = require('fs')

// 导入上传远程仓库的工具函数
const myoss = require('../../utils/myoss')

// 配置变量
const curNav = 5
const base_path_pic = 'http://admi-yuliner.oss-cn-hangzhou.aliyuncs.com/'

// 获取列表数据
userorder.get('/order', (req, res) => {
   let str1 = 'orders.id, orders.order_num, orders.food_totalprice, orders.username, orders.address_id,'
   let str2 = 'address.realname, address.phone, address.address'
   const sql = `SELECT ${str1 + str2} FROM orders,address WHERE orders.address_id=address.id`
   db.query(sql, (err, result) => {
      res.render('UserOrder/userorder', {
         user: req.session.uname || '',
         curNav: 5,
         data: result
      })
   })
})

// 查看订单详细
userorder.get('/orderdetail', (req, res) => {
   const { id } = req.query
   const sql = `SELECT * FROM orders_goods WHERE orders_id=${id}`
   db.query(sql, (err, result) => {
      res.render('UserOrder/orderdetail', {
         user: req.session.uname || '',
         curNav: 5,
         host: base_path_pic,
         data: result
      })
   })
})

// 更新订单
userorder.get('/updateorder', (req, res) => {
   const { id } = req.query
   const sql = `SELECT * FROM orders_goods WHERE id=${id}`
   db.query(sql, (err, result) => {
      res.render('UserOrder/updateorder', {
         user: req.session.uname,
         curNav,
         host: base_path_pic,
         data: result[0]
      })
   })
})
userorder.post('/doupdateorder', async (req, res) => {
   const { params, files } = await getformidable(req)
   const { foodname, pic, count, id } = params
   const { newFilename, size, filepath } = files.newpic
   let sql = ''
   // 上传云端
   if (size > 0) {
      console.log('上传云端')
      sql = `UPDATE orders_goods SET foodname='${foodname}', pic='${newFilename}', count='${count}' WHERE id=${id}`
      // 更新数据库
      db.query(sql, async (err, result) => {
         if (result.affectedRows > 0) {
            await myoss.deldata(pic) // 删除原始图片
            await myoss.pushdata(newFilename, filepath) //上传新图
            fs.unlinkSync(filepath)
            res.send(`<script>alert('更新成功');window.location.href='/userorder/order'</script>`)
         } else {
            res.send(`<script>alert('更新失败');window.location.href='/userorder/updateorder?id=${id}'</script>`)
         }
      })
   } else {
      console.log('更新本地')
      sql = `UPDATE orders_goods SET foodname='${foodname}', pic='${pic}', count='${count}' WHERE id=${id}`
      // 更新数据库
      db.query(sql, (err, result) => {
         if (result.affectedRows > 0) {
            fs.unlinkSync(filepath)
            res.send(`<script>alert('更新成功');window.location.href='/userorder/order'</script>`)
         } else {
            res.send(`<script>alert('更新失败');window.location.href='/userorder/updateorder?id=${id}'</script>`)
         }
      })
   }
})

// 搜索功能
userorder.get('/search', (req, res) => {
   const { kwd } = req.query
   let str1 = 'orders.id, orders.order_num, orders.food_totalprice, orders.username, orders.address_id,'
   let str2 = 'address.realname, address.phone, address.address'
   const sql = `SELECT ${str1 + str2} FROM orders,address WHERE orders.address_id=address.id`
   db.query(sql, (err, result) => {
      if (result.length > 0) {
         let data = result.filter((item) => {
            return item.username.includes(kwd) || item.address.includes(kwd)
         })
         res.render('UserOrder/ordersearch', {
            user: req.session.uname || '',
            curNav: 5,
            data: data
         })
      }
   })
})

module.exports = userorder